package com.hitearth.ccbrower.webview;

import android.graphics.Bitmap;
import android.util.Log;

import android.webkit.WebViewClient;

import com.hitearth.ccbrower.MainActivity;

import android.webkit.*;
import android.widget.Toast;

import com.hitearth.ccbrower.*;


public class HybridWebViewClient extends WebViewClient {
    private int count = 0;
    private String firstReqUrlHost;
    MainActivity act;

    public HybridWebViewClient(MainActivity act) {
        this.act = act;
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        return GetRes(request.getUrl().toString());
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        return GetRes(url);
    }

    private WebResourceResponse GetRes(String url) {
        WebResourceResponse response = null;
        if (url.startsWith("file://")) {
            return response;
        }
        if (!cc(url)) {
            count++;
            response = new WebResourceResponse("image/png", "UTF-8", null);

        }
        return response;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        firstReqUrlHost = getHost(url);
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        firstReqUrlHost = getHost(url);
        count = 0;
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        if (count > 0) {
            Toast.makeText(act, count + " 个", Toast.LENGTH_SHORT).show();
            count = 0;
        }
        if (!url.equals(((UrlText) act.findViewById(R.id.urlText1)).getText())) {
            act.storeURL=url;
            ((UrlText) act.findViewById(R.id.urlText1)).setText(url);
        }
        super.onPageFinished(view, url);
    }


    private boolean cc(String dest) {
        if (firstReqUrlHost == null) return true;
        String destHost = getHost(dest);
        if (destHost == null) return true;
        if (destHost.length() > firstReqUrlHost.length())
            return destHost.endsWith(firstReqUrlHost);
        else
            return firstReqUrlHost.endsWith(destHost);
    }

    private String localhost = "localhost";

    private String getHost(String url) {
        if (url == null) return null;
        if (url.startsWith("file:///")) return localhost;

        int start = url.indexOf("//") + 2;
        int num2 = url.indexOf("/", start);
        if (num2 == -1) num2 = url.length();

        String host = url.substring(start, num2);

        return host;
    }
}
